local skynet = require "skynet"
--fixme 这里为什么要加skynet.?

require "hand_pb"

local hand_msg = {}

function hand_msg:Init()
    skynet.error("Init!!!!")
end

local function write_package(conn_type, fd, msg)
    local tmpmsg, sz
    if conn_type == __CONN_TYPE_WEBSOCKET___ then
        tmpmsg, sz = wsnetpack.pack(msg)
    elseif conn_type == __CONN_TYPE_SOCKET___ then
        tmpmsg, sz = netpack.pack(msg)
    else
        skynet.error('write_package conn_type error', conn_type, fd)
        return
    end

    local ok, err = pcall(socket.write, fd, tmpmsg, sz)
    if not ok then
        skynet.error('socket.write faild:', err)
        return
    end
    return true
end

function hand_msg:SendMsg(conn_type, fd, pack_name, msg_name, msg_content)
    local msgbody = {[msg_name] = msg_content}
    --local pack_pkid = pack_helper.get_pkid(pack_name)
    local pack_id = 5
    if not pack_id then
        skynet.error('send message faild no found pack_name:', pack_name, msg_name, msgbody)
        return
    end

    --local msg = XteaEncode(pack_name, msgbody, pack_id)
    if msg then
        return write_package(conn_type, fd, msg)
    else
        skynet.error('pack_message faild :', pack_name, msg_name)
    end
    return msgbody
end

skynet.start(function()
    skynet.dispatch("lua", function(session, address, cmd, ...)
        log.info("del msg dispatch cmd=", cmd)
        local f = hand_msg[cmd]
        if f then
            skynet.ret(skynet.pack(f(hand_msg, ...)))
        else
            error(string.format("Unknown command %s", tostring(cmd)))
        end
    end)

    hand_msg:Init()
end)


return hand_msg